import PictureUploader from '@/components/PictureUploader';
import {doAdd, getCategoryUsingGet} from '@/services/backend/generatorController';
import {history, useSearchParams} from '@@/exports';
import type {ProFormInstance} from '@ant-design/pro-components';
import {ProCard, ProFormSelect, ProFormText, ProFormTextArea, StepsForm,} from '@ant-design/pro-components';
import {ProFormItem} from '@ant-design/pro-form';
import {message} from 'antd';
import React, {useRef, useState} from 'react';

/**
 * 创建生成器页面
 * @constructor
 */
const GeneratorAddPage: React.FC = () => {
  const [searchParams] = useSearchParams();
  const id = searchParams.get('id');
  const formRef = useRef<ProFormInstance>();
  // 记录表单已填数据
  const [basicInfo, setBasicInfo] = useState<API.GoodsAddQuery>();

  /**
   * 提交
   * @param values
   */
  const doSubmit = async (values: API.GoodsAddQuery) => {
    const res=await doAdd(values);
    if(res){
      message.success("添加成功！！！");
      history.push( '/');
    }else{
      message.error("添加失败！！！");
    }
  };

  return (
    <ProCard>
      {/* 创建或者已加载要更新的数据时，才渲染表单，顺利填充默认值 */}
      {(!id) && (
        <StepsForm<API.GoodsAddQuery>
          formRef={formRef}
          onFinish={doSubmit}
        >
          <StepsForm.StepForm
            name="base"
            title="基本信息"
            onFinish={async (values) => {
              console.log("aaaa",values);
              setBasicInfo(values as API.GoodsAddQuery);
              return true;
            }}
          >
            <ProFormText name="goodsName" label="名称" placeholder="请输入名称" />
            <ProFormTextArea name="goodsDescription" label="描述" placeholder="请输入描述" />
            <ProFormText name="price" label="价格" placeholder="请输入商品价格" />
            <ProFormText name="userAccount" label="用户账号" placeholder="请输入用户账号" />
            <ProFormSelect
              name="typeId"
              label="商品类型"
              placeholder="请选择商品类型"
              request={async ()=>{
                try {
                  const res= await getCategoryUsingGet();
                  return res||[]
                } catch (error: any) {
                  message.error('加载数据失败，' + error.message);
                }
              }}
            />
            <ProFormText name="addTypeName" label="新增商品类型" placeholder="新增商品类型" />
            <ProFormItem label="图片" name="goodsImage">
              <PictureUploader biz="generator_picture" />
            </ProFormItem>
          </StepsForm.StepForm>
        </StepsForm>
      )}
    </ProCard>
  );
};

export default GeneratorAddPage;
